package com.joeyzh.iframe.db;

import android.content.Context;

import com.joey.base.util.LogUtils;
import com.joeyzh.BuildConfig;
import com.joeyzh.iframe.db.dao.DaoMaster;
import com.joeyzh.iframe.db.dao.DaoSession;

import org.greenrobot.greendao.query.QueryBuilder;

/**
 * 创建数据库、数据表帮助类
 */
public class DBManagerUtil {

    private static final String TAG = DBManagerUtil.class.getSimpleName();
    private static final String DB_NAME = BuildConfig.APPLICATION_ID;

    private Context context;

    //多线程中要被共享的使用volatile关键字修饰
    private volatile static DBManagerUtil manager;
    private static DaoMaster sDaoMaster;
    private static DaoMaster.DevOpenHelper sHelper;
    private static DaoSession sDaoSession;


    private DBManagerUtil() {

    }

    /**
     * 单例模式获得操作数据库对象
     *
     * @return
     */
    public static synchronized DBManagerUtil getInstance() {
        if (manager != null) {
            LogUtils.a("init");
            return manager;
        }
        synchronized (DBManagerUtil.class) {
            if (manager == null) {
                LogUtils.a("init manager == null");
                manager = new DBManagerUtil();
            }
            LogUtils.a("init manager != null");

            return manager;
        }
    }

    public synchronized void init(Context context) {
        if (sHelper != null) {
            LogUtils.a("init sHelper != null");
            return;
        }
        synchronized (DBManagerUtil.this) {
            if (sHelper == null) {
                this.context = context;
                sHelper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
                sDaoMaster = new DaoMaster(sHelper.getWritableDatabase());
                sDaoSession = sDaoMaster.newSession();
                LogUtils.a("init sHelper == null");
            }
        }

    }

    /**
     * 判断是否有存在数据库，如果没有则创建
     *
     * @return
     */
    public DaoMaster getDaoMaster() {
        return sDaoMaster;

    }

    /**
     * 完成对数据库的添加、删除、修改、查询操作，仅仅是一个接口
     *
     * @return
     */
    public DaoSession getDaoSession() {
        return sDaoSession;
    }

    /**
     * 打开输出日志，默认关闭
     */
    public void setDebug() {
        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;
    }

    /**
     * 关闭所有的操作，数据库开启后，使用完毕要关闭
     */
    public void closeConnection() {
        closeHelper();
        closeDaoSession();
    }

    public void closeHelper() {
        if (sHelper != null) {
            sHelper.close();
            sHelper = null;
        }
    }

    public void closeDaoSession() {
        if (sDaoSession != null) {
            sDaoSession.clear();
            sDaoSession = null;
        }
    }
}
